/**
* @Title: KeyGenerator.java
* @Package com.apply.tool.util
* @Description: TODO(用一句话描述该文件做什么)
* @author TangCai
* @date 2017年4月26日 下午4:34:13
* @version V1.0
*/


package com.lh.common.utils;


import com.lh.common.enums.AfterSaleOrderTypeEnum;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* @ClassName: KeyGenerator
* @Description: 主键生成器(这里用一句话描述这个类的作用)
* @author TangCai
* @date 2017年4月26日 下午4:34:13
*
*/

public class KeyGenerator {
	private static final long ONE_STEP = 10000;
    private static final Lock LOCK = new ReentrantLock();
    private static long lastTime = System.currentTimeMillis();
    private static short lastCount = 0;
    private static int count = 0;

    @SuppressWarnings("finally")
    public static String nextId() {
        LOCK.lock();
        try {
            if (lastCount == ONE_STEP) {
                boolean done = false;
                while (!done) {
                    long now = System.currentTimeMillis();
                    if (now == lastTime) {
                        try {
                            Thread.currentThread();
                            Thread.sleep(1);
                        } catch (java.lang.InterruptedException e) { }
                        continue;
                    } else {
                        lastTime = now;
                        lastCount = 0;
                        done = true;
                    }
                }
            }
            count = lastCount++;
            return lastTime+""+ String.format("%04d",count);
        }
        finally {
            LOCK.unlock();
        }
    }

    /*
    * 生成售后订单ID
    * type 为售后SH  或 退款 TK
    * 退款编号格式：TK201910101212123456，TK+年月日时分+任意六位数
    *售后编号格式：SH201910101212123456，SH+年月日时分+任意六位数
    * */
    public static String getAfterSaleOrderID(AfterSaleOrderTypeEnum type){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String dateStr = sdf.format(new Date());
        String random =  RandomString.getNumber(6);
        return type + dateStr + random;
    }
    public static void main(String[] args)
    {
        //测试
//        for(int i=0;i<10000;i++) {
//            System.out.println(nextId());
//        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String dateStr = sdf.format(new Date());
        String random =  RandomString.getNumber(6);
        System.out.println(AfterSaleOrderTypeEnum.SH+dateStr + random);
    }
}
